<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模拟重力</title>
</head>
<!--当键盘按下之后，调用test方法-->
<body>
<canvas id="test" width="1000px" height="900px" style="background-color: black;"></canvas>
<script type="text/javascript">
    var canvas = document.getElementById("test");
    var cxt = canvas.getContext("2d");
    var BallX = 30;
    var BallY = 30;
    var g = 9.8;
    var t = 0;
    var anoTimer;
    const drawBall = () => {
        // 画出红色小球
        cxt.beginPath();
        cxt.fillStyle = "red";
        cxt.arc(BallX, BallY, 10, 0, 360);
        cxt.closePath();    //画图时一定要开始和闭合路径，防止出现一些奇怪的问题
        cxt.fill();
    };
    var timer = setInterval(() => {
            cxt.clearRect(0, 0, 1000, 900);
            drawBall();
            t = t + 0.02;
            var h = g * t * t / 2
            BallY = BallY + h;
            if (BallY > 900) {
                BallY = 890;
                cxt.clearRect(0, 0, 1000, 900);
                drawBall();
                clearInterval(timer)
                anoTimer = setInterval(() => {
                        t = t - 0.03;
                        BallY = BallY - g * t * t / 2;
                        cxt.clearRect(0, 0, 1000, 900);
                        drawBall()
                        console.log(t)
                        if (t <= 0) {
                            clearInterval(anoTimer);
                            var tt = setInterval(() => {
                                    cxt.clearRect(0, 0, 1000, 900);
                                    drawBall();
                                    t = t + 0.02;
                                    var h = g * t * t / 2
                                    BallY = BallY + h;
                                    if (BallY > 900) {
                                        BallY = 890;
                                        cxt.clearRect(0, 0, 1000, 900);
                                        drawBall();
                                        clearInterval(tt)
                                    }
                                },
                                20
                            )
                        }
                    },
                    20
                )
            } else {

            }
        },
        20
    )
    drawBall();

</script>
</body>
</html>